package com.seecen.cywbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.seecen.cywbackend.mapper.*;
import com.seecen.cywbackend.pojo.*;
import com.seecen.cywbackend.pojo.vo.DynamicQuery;
import com.seecen.cywbackend.pojo.vo.DynamicVO;
import com.seecen.cywbackend.utils.PageResult;
import com.seecen.cywbackend.service.DynamicService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author lenovo
* @description 针对表【t_dynamic(圈子消息表)】的数据库操作Service实现
* @createDate 2025-03-21 16:26:00
*/
@Service
public class DynamicServiceImpl extends ServiceImpl<DynamicMapper, Dynamic>  implements DynamicService {
    @Resource
    private DynamicMapper dynamicMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private FollowsMapper followsMapper;
    @Resource
    private GroupMapper groupMapper;
    @Resource
    private LikeMapper likeMapper;
    @Resource
    private FavoriteMapper favoriteMapper;

    @Override
    @Transactional
    public PageResult<DynamicVO> pageDynamicList(DynamicQuery query) {
        Page<Dynamic> page = new Page<>(query.getCurrent(), query.getSize());
        LambdaQueryWrapper<Dynamic> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(query.getGroupId()!=null, Dynamic::getGroupId, query.getGroupId()).orderByDesc(Dynamic::getCreateTime);
        //tabType 1-关注, 2-最新, 3-新评论, 4-精华
        if(query.getTabType()!=null){
            switch (query.getTabType()){
                case 1:
                    wrapper.inSql(Dynamic::getCreator, "select target_id from t_follows where user_id = " + query.getCurrentUserId()+" and target_type="+1)
                            .or()
                            .inSql(Dynamic::getGroupId, "select target_id from t_follows where user_id = " + query.getCurrentUserId()+" and target_type="+2);
                    break;
                case 2:
                    break;
                case 3:
                    //子查询评论表，查询出评论创建时间到当前时间不超过24小时的动态id
                    wrapper.inSql(Dynamic::getId, "select dynamic_id from t_comment where create_time > DATE_SUB(NOW(), INTERVAL 24 HOUR)");
                    break;
                case 4:
                    wrapper.eq(Dynamic::getIsEssence, 1);
                    break;
            }
        }
        IPage<Dynamic> dynamicPage = dynamicMapper.selectPage(page, wrapper);
        List<DynamicVO> voList = dynamicPage.getRecords().stream().map(dynamic -> {
            DynamicVO vo = new DynamicVO();
            BeanUtils.copyProperties(dynamic, vo);
            ObjectMapper objectMapper = new ObjectMapper();
            //处理图片
            try {
                if(dynamic.getThumbs() != null) vo.setImages(objectMapper.readValue(dynamic.getThumbs(), List.class));
            }catch (Exception e){
            }
            // 查询用户信息
            User user = userMapper.selectById(dynamic.getCreator());
            vo.setNickname(user.getNickname());
            vo.setAvatar(user.getAvatar());
            vo.setGroupId(dynamic.getGroupId());
            vo.setGroupName(groupMapper.selectById(dynamic.getGroupId()).getName());
            vo.setLikeCount(dynamic.getLikeCount());
            vo.setCommentCount(dynamic.getCommentCount());
            vo.setFavoriteCount(dynamic.getFavoriteCount());
            // 查询关注状态
            LambdaQueryWrapper<Follows> followWrapper = new LambdaQueryWrapper<>();
            followWrapper.eq(Follows::getUserId, query.getCurrentUserId())
                    .eq(Follows::getTargetId, dynamic.getCreator());
            vo.setIsFollowed(followsMapper.exists(followWrapper));
            // 查询点赞状态
            LambdaQueryWrapper<Like> likeWrapper = new LambdaQueryWrapper<>();
            likeWrapper.eq(Like::getUserId, query.getCurrentUserId())
                    .eq(Like::getTargetId, dynamic.getId())
                    .eq(Like::getTargetType, 1);
            vo.setIsLiked(likeMapper.exists(likeWrapper));
            // 查询收藏状态
            LambdaQueryWrapper<Favorite> favWrapper = new LambdaQueryWrapper<>();
            favWrapper.eq(Favorite::getUserId, query.getCurrentUserId())
                    .eq(Favorite::getTargetId, dynamic.getId())
                    .eq(Favorite::getTargetType, 3);
            vo.setIsFavorited(favoriteMapper.exists(favWrapper));
            return vo;
        }).collect(Collectors.toList());
        return new PageResult<>(
                voList,
                dynamicPage.getTotal(),
                dynamicPage.getSize(),
                dynamicPage.getCurrent(),
                dynamicPage.getPages()
        );
    }
}




